home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / epsilon / view.py < prev   
Text File  |  2009-03-13  |  2KB  |  54 lines

  1. # -*- test-case-name: epsilon.test.test_view -*-
  2.  
  3. """
  4. Utility functionality for creating wrapping sequences so as to transform
  5. their indices in some manner.
  6. """
  7.  
  8. class SlicedView(object):
  9.     """
  10.     Wrapper around a sequence which allows indexing and non-extended
  11.     slicing, adjusting all indices using a transformation defined by a
  12.     L{slice} object.
  13.  
  14.     For example::
  15.  
  16.         s = ['a', 'b']
  17.         t = SlicedView(s, slice(1, None))
  18.         t[0] == 'b'
  19.  
  20.     @ivar sequence: The underlying sequence from which to retrieve elements.
  21.     @ivar bounds: A C{slice} instance defining the boundaries of this view.
  22.     """
  23.  
  24.     def __init__(self, sequence, bounds):
  25.         self.sequence = sequence
  26.         self.bounds = bounds
  27.  
  28.  
  29.     def _getIndices(self):
  30.         start, stop, step = self.bounds.indices(len(self.sequence))
  31.         indices = xrange(start, stop, step)
  32.         return indices
  33.  
  34.  
  35.     def __getitem__(self, index):
  36.         """
  37.         Compute the index in the underlying sequence of the given view index
  38.         and return the corresponding element.
  39.  
  40.         @raise IndexError: If C{index} is out of bounds for the view.
  41.         @raise ValueError: If C{self.bounds} is out of bounds for
  42.         C{self.sequence}.
  43.         """
  44.         if isinstance(index, slice):
  45.             return SlicedView(self, index)
  46.         return self.sequence[self._getIndices()[index]]
  47.  
  48.  
  49.     def __len__(self):
  50.         """
  51.         Compute the length of this view onto the sequence and return it.
  52.         """
  53.         return len(self._getIndices())
  54.